package java_thinking.unit_15._15_8;

import java.lang.reflect.Constructor;

/**
 * @Description :   使用类型标签与反射来创建一个方法，它将使用newInstance
 *                  的参数版本来创建某个类的对象，这个类拥有一个具有参数的构造器
 * @author: cww
 * @DateTime: 2019-04-05 10:54
 */

/**
 * @author asd730520@live.com
 */
public class ClassAsFactory1<T> {
    Class<T> kind;
    public ClassAsFactory1(Class<T> kind){
        this.kind = kind;
    }

    public T create(int arg) {
        try {
            for (Constructor<?> constructor:kind.getConstructors()){
                Class<?>[] params = constructor.getParameterTypes();
                if (params.length == 1 ){
                    /**
                     * 这里用的cast()
                     */
                    return kind.cast(constructor.newInstance(arg));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}

class  E22 {
    public static void main(String[] args) {
        ClassAsFactory1<Employee1> factory1 = new ClassAsFactory1<>(Employee1.class);
        Employee1 employee = factory1.create(10);
        if (employee == null) {
            System.out.println("Employee cannot be instantiated!");
        }
        ClassAsFactory1<Integer> factory2 = new ClassAsFactory1<>(Integer.class);
        Integer integer = factory2.create(4);
        if (integer == null) {
            System.out.println("Integer cannot be instantiated!");
        }
    }
}

class Employee1 {
    private String i;
    public Employee1(String i) {
        System.out.println(i);
        this.i = i;
    }
}
